// pages/my-group-edit/my-group-edit.ts
import { getPublishDetail, editPublish } from '../../../api/publish.js'
import { getCategoryNames, getProductsByCategory } from '../../../config/product-categories.js'
import { goBack } from '../../../config/pages.js'

interface SpecItem {
  mm: string;
  m: string;
}

interface FormData {
  product_category: string;
  product_name: string;
  product_model: string;
  specs: SpecItem[];
  province: string;
  city: string;
  district: string;
  province_id: number;
  city_id: number;
  district_id: number;
  total_amount: string;
  remark: string;
  contact_name: string;
  contact_phone: string;
  contact_email: string;
  detail_address: string;
}

Page({
  data: {
    id: '',
    loading: true,
    publishType: 'group', // 单据类型
    // 表单数据
    formData: {
      product_category: '',
      product_name: '',
      product_model: '',
      specs: [
        { mm: '', m: '' }
      ],
      province: '',
      city: '',
      district: '',
      province_id: 0,
      city_id: 0,
      district_id: 0,
      total_amount: '',
      remark: '',
      contact_name: '',
      contact_phone: '',
      contact_email: '',
      detail_address: ''
    } as FormData,
    
    // 选择器数据
    categoryList: getCategoryNames(),
    productList: [] as string[],
    showCategoryPicker: false,
    showProductPicker: false,
    categoryIndex: 0,
    productIndex: 0,
    
    // 技术参数文件
    techParamsFile: null as any,
    
    // 提交状态
    submitting: false
  },

  onLoad(options: any) {
    const { id } = options;
    if (id) {
      this.setData({ id });
      this.loadDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none',
      });
      setTimeout(() => {
        goBack();
      }, 1500);
    }
  },

  // 加载详情数据
  async loadDetail() {
    this.setData({ loading: true });

    try {
      const res = await getPublishDetail(Number(this.data.id));

      if ((res.status === 200 || res.code === 200) && res.data) {
        const detail = res.data;
        
        // 保存单据类型
        if (detail.type) {
          this.setData({ publishType: detail.type });
        }
        
        // 解析规格数据
        let specs = [{ mm: '', m: '' }];
        if (detail.spec) {
          try {
            const parsedSpecs = typeof detail.spec === 'string' 
              ? JSON.parse(detail.spec) 
              : detail.spec;
            if (Array.isArray(parsedSpecs) && parsedSpecs.length > 0) {
              specs = parsedSpecs;
            }
          } catch (e) {
            console.error('解析规格数据失败:', e);
          }
        }
        
        // 设置产品列表
        const categoryIndex = this.data.categoryList.indexOf(detail.product_category || '');
        const productList = detail.product_category 
          ? getProductsByCategory(detail.product_category) 
          : [];
        const productIndex = productList.indexOf(detail.product_name || '');
        
        // 解析技术参数数据
        let techParamsFile = null;
        if (detail.tech_params_atts) {
          try {
            const parsedParams = typeof detail.tech_params_atts === 'string' 
              ? JSON.parse(detail.tech_params_atts) 
              : detail.tech_params_atts;
            if (Array.isArray(parsedParams) && parsedParams.length > 0) {
              techParamsFile = parsedParams[0];
              console.log('解析技术参数成功:', techParamsFile);
            }
          } catch (e) {
            console.error('解析技术参数失败:', e);
          }
        }
        
        // 填充表单数据
        this.setData({
          formData: {
            product_category: detail.product_category || '',
            product_name: detail.product_name || '',
            product_model: detail.product_model || '',
            specs: specs,
            province: detail.province || '',
            city: detail.city || '',
            district: detail.district || '',
            province_id: detail.province_id || 0,
            city_id: detail.city_id || 0,
            district_id: detail.district_id || 0,
            total_amount: detail.total_amount || '',
            remark: detail.remark || '',
            contact_name: detail.contact_name || '',
            contact_phone: detail.contact_phone || '',
            contact_email: detail.contact_email || '',
            detail_address: detail.detail_address || ''
          },
          productList: productList,
          categoryIndex: categoryIndex >= 0 ? categoryIndex : 0,
          productIndex: productIndex >= 0 ? productIndex : 0,
          techParamsFile: techParamsFile,
          loading: false,
        });
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none',
        });
        this.setData({ loading: false });
      }
    } catch (error: any) {
      console.error('加载详情失败:', error);
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.message || '加载失败'),
        icon: 'none',
      });
      this.setData({ loading: false });
    }
  },

  // 型号输入
  onModelInput(e: any) {
    this.setData({
      'formData.product_model': e.detail.value
    });
  },

  // 总量输入
  onTotalAmountInput(e: any) {
    this.setData({
      'formData.total_amount': e.detail.value
    });
  },

  // 备注输入
  onRemarkInput(e: any) {
    this.setData({
      'formData.remark': e.detail.value
    });
  },

  // 联系人输入
  onContactNameInput(e: any) {
    this.setData({
      'formData.contact_name': e.detail.value
    });
  },

  // 联系电话输入
  onContactPhoneInput(e: any) {
    this.setData({
      'formData.contact_phone': e.detail.value
    });
  },

  // 邮箱输入
  onEmailInput(e: any) {
    this.setData({
      'formData.contact_email': e.detail.value
    });
  },

  // 详细地址输入
  onDetailAddressInput(e: any) {
    this.setData({
      'formData.detail_address': e.detail.value
    });
  },

  // 显示产品类别选择器
  showCategoryPicker() {
    this.setData({
      showCategoryPicker: true
    });
  },

  // 显示产品名称选择器
  showProductPicker() {
    this.setData({
      showProductPicker: true
    });
  },

  // 产品类别选择器变化
  onCategoryPickerChange(e: any) {
    const index = e.detail.value[0];
    this.setData({
      categoryIndex: index
    });
  },

  // 产品名称选择器变化
  onProductPickerChange(e: any) {
    const index = e.detail.value[0];
    this.setData({
      productIndex: index
    });
  },

  // 隐藏产品类别选择器
  hideCategoryPicker() {
    this.setData({
      showCategoryPicker: false
    });
  },

  // 确认产品类别选择
  confirmCategoryPicker() {
    const index = this.data.categoryIndex || 0;
    const category = this.data.categoryList[index];
    const products = getProductsByCategory(category);
    this.setData({
      'formData.product_category': category,
      'formData.product_name': '', // 清空产品名称
      productList: products,
      productIndex: 0,
      showCategoryPicker: false
    });
  },

  // 隐藏产品名称选择器
  hideProductPicker() {
    this.setData({
      showProductPicker: false
    });
  },

  // 确认产品名称选择
  confirmProductPicker() {
    const index = this.data.productIndex || 0;
    const product = this.data.productList[index];
    this.setData({
      'formData.product_name': product,
      showProductPicker: false
    });
  },

  // 规格输入
  onSpecInput(e: any) {
    const { index, type } = e.currentTarget.dataset;
    const value = e.detail.value;
    const specs = [...this.data.formData.specs];
    (specs[index] as any)[type] = value;
    this.setData({
      'formData.specs': specs
    });
  },

  // 添加规格项
  addSpecItem() {
    const specs = [...this.data.formData.specs];
    specs.push({ mm: '', m: '' } as SpecItem);
    this.setData({
      'formData.specs': specs
    });
  },

  // 删除规格项
  removeSpecItem(e: any) {
    const index = e.currentTarget.dataset.index;
    const specs = [...this.data.formData.specs];
    specs.splice(index, 1);
    this.setData({
      'formData.specs': specs
    });
  },

  // 地址选择变化
  onAddressChange(e: any) {
    const { address } = e.detail;
    if (address) {
      this.setData({
        'formData.province': address.province,
        'formData.city': address.city,
        'formData.district': address.district,
        'formData.province_id': address.province_id,
        'formData.city_id': address.city_id,
        'formData.district_id': address.district_id
      });
    }
  },

  // 技术参数上传成功回调
  onTechParamsUploadSuccess(e: any) {
    const { fileData } = e.detail;
    console.log('技术参数上传成功:', fileData);
    
    this.setData({
      techParamsFile: fileData
    });
  },

  // 技术参数删除回调
  onTechParamsRemove() {
    console.log('删除技术参数文件');
    
    this.setData({
      techParamsFile: null
    });
  },

  // 保存编辑
  async saveEdit() {
    // 表单验证
    if (!this.validateForm()) {
      return;
    }

    console.log('保存编辑:', this.data.formData);

    this.setData({ submitting: true });

    // 显示加载中
    wx.showLoading({
      title: '保存中...'
    });
    
    try {
      // 准备提交数据
      const submitData: any = {
        ...this.data.formData,
        type: this.data.publishType, // 添加单据类型
        spec: JSON.stringify(this.data.formData.specs || [])
      };
      
      // 添加技术参数信息（如果有上传）
      if (this.data.techParamsFile) {
        submitData.tech_params_atts = JSON.stringify([{
          url: this.data.techParamsFile.url,
          name: this.data.techParamsFile.name
        }]);
        submitData.tech_params_file_name = this.data.techParamsFile.name;
      }

      // 调用API编辑拼单
      const result = await editPublish(Number(this.data.id), submitData);
      
      if (result.status === 200 || result.code === 200) {
        wx.hideLoading();
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        setTimeout(() => {
          goBack();
        }, 1500);
      } else {
        wx.hideLoading();
        wx.showToast({
          title: result.msg || '保存失败',
          icon: 'none'
        });
        this.setData({ submitting: false });
      }
    } catch (error: any) {
      console.error('保存失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '保存失败，请重试'),
        icon: 'none'
      });
      this.setData({ submitting: false });
    }
  },

  // 表单验证
  validateForm(): boolean {
    const { formData } = this.data;
    
    if (!formData.product_category) {
      wx.showToast({
        title: '请选择产品类别',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.product_name) {
      wx.showToast({
        title: '请选择产品名称',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.product_model.trim()) {
      wx.showToast({
        title: '请输入产品型号',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.province) {
      wx.showToast({
        title: '请选择发货地址',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.total_amount.trim()) {
      wx.showToast({
        title: '请输入总量',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.contact_name.trim()) {
      wx.showToast({
        title: '请输入联系人姓名',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.contact_phone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      });
      return false;
    }
    
    return true;
  }
});

